<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 */
class Jiu99Controller extends PayController{
    protected $config;
	protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $ismobile = isMobile();

        $return = $this->orderadd( $parameter );
        $data['userName'] = $this->config['appid'];
        $data['merchantLoginName'] = $this->config['mch_id'];
        $data['orderMoney'] = strval(number_format($return['amount'],2,'.',''));
        switch ($this->config['paytype']){
            case 1:
            case 2:
                $data['payMode'] = '4';
                break;
            case 3:
            case 4:
            case 17:
            case 18:
                $data['payMode'] = '3';
                break;
            default:
                $this->showmessage('此通道暂不支持次支付方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['otherOrderNo'] = $return['orderid'];
        $data['backUrl'] = urlencode($return['notifyurl']);

        ksort($data);
        $json = json_encode($data,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        $str = $this->config['signkey'] . 'user/api/createOrder' . $json . date("Ymd",time());
        $data['token'] = md5($str);

        $res = curl($this->config['gateway'], httpstr($data));
        $res = json_decode($res, true);

        /*echo "<pre/>"; print_r($data);
        echo "请求地址：" . $this->config['gateway'] . '<br/>';
        print_r($res); exit;*/

        $code = $res['url'];
        if(!$code){
            if($res['msg']){
                $this->showmessage($res['msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $paytype = transArr( C("PAYTYPES"), "id");
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));
        switch($this->config['paytype']){
            //微信
            case 1:
            case 2:
                if($ismobile){
                    header("Location:{$code}");
                }else{
                    $this->display("WeiXin/weixin");
                }
                break;
            //支付宝扫码
            case 3:
            case 4:
            case 17:
            case 18:
                header("Location:{$code}");
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
        //$this->debug_callback();
        if(!$this->checkip(getIP(),['47.92.77.184'])){
            exit("wrong");
        }

        $p = file_get_contents("php://input");

        $p = json_decode($p, true);

        if(!$p || empty($p)){
            exit("");
        }

        //获取订单信息
        $orderid = $p['otherOrderNo'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "pay_orderid_rd"=>htmlspecialchars($p['trade_no']),
            "pay_true" => floatval($p['receipt_amount']),
        ));

        if(($p['receipt_amount'] - $p['total_amount']) >= 1){
            exit("money_wrong");
        }

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        if($p['trade_status'] !== 'TRADE_SUCCESS'){
            exit("fail");
        }
        $sign = $p['token'];

        $param = [];
        $param['trade_no'] = $p['trade_no'];
        $param['buyer_logon_id'] = $p['buyer_logon_id'];
        $param['trade_status'] = $p['trade_status'];
        $param['receipt_amount'] = $p['receipt_amount'];
        $param['otherOrderNo'] = $p['otherOrderNo'];

        ksort($param);
        $json = json_encode($param,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $str = $this->config['signkey'] . $json . date("Ymd",time());
        $sign2 = md5($str);

        if($sign !== $sign2){
            echo 'sign_wrong';exit;
        }

        //回调成功
		$this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}